package com.powernode.controller;

import com.powernode.entity.Goods;
import com.powernode.service.GoodsService;
import com.powernode.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 商品 controller
 */
@Controller
@Slf4j
@RequestMapping("/goods/")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    /**
     * 获取待秒杀列表
     *
     * @return
     */
    @GetMapping("/list")
    public ModelAndView loadGoodsList() {
        log.info("查询秒杀商品列表功能");
        // 查询 商品数据
        List<Goods> goodsList = goodsService.loadGoodsList();
        // 创建modelandview对象
        ModelAndView modelAndView = new ModelAndView();
        // 给该对象添加展示数据
        modelAndView.addObject("goodsList" , goodsList);
        modelAndView.setViewName("list");
        return modelAndView;
    }


    /**
     * 查询商品详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ModelAndView loadGoodsById(@PathVariable(value = "id") Integer id) {
        log.info("要查询商品详情的id : {}" , id);
        // 获取对应商品
        Goods goods = goodsService.loadGoodsById(id);
        //随机码设置成null，防止被黑客提前获取
        goods.setRandomName(null);
        ModelAndView modelAndView = new ModelAndView("detail");
        modelAndView.addObject("goods", goods);
        modelAndView.addObject("nowTime", System.currentTimeMillis());
        return modelAndView;
    }

    @GetMapping("/time/{id}")
    @ResponseBody
    public HttpResult getGoodsTime(@PathVariable(value = "id") Integer id) {
        log.info("获取秒杀商品路径的随机码 , id :{}" , id);
        Goods goods = goodsService.loadGoodsById(id);
        // 判断当前是否在 秒杀时间段
        long currentTime = System.currentTimeMillis();
        long startTime = goods.getStartTime().getTime();
        long endTime = goods.getEndTime().getTime();
        if (currentTime < startTime) {
            // 秒杀还未开始呢
            return HttpResult.ERROR("秒杀还没有还是勒, 你别急 , 稍后再试");
        }
        if (currentTime > endTime) {
            return HttpResult.ERROR("你来晚了 , 秒杀已经结束 , good bay");
        }
        // 秒杀正在进行中 , 返回对应结果
        return HttpResult.SUCCESS("秒杀正在进行中" , goods.getRandomName());
    }


}
